/*
 * Copyright (c) 2021-2031, 河北计全科技有限公司 (https://www.jeequan.com & jeequan@126.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.lingyangwl.agile.pay.pay.channel.wxpay.paywayV3;

import cn.lingyangwl.framework.tool.core.StringUtils;
import cn.lingyangwl.agile.pay.constant.PayWayCodeEnum;
import cn.lingyangwl.agile.pay.model.entity.PayOrder;
import cn.lingyangwl.agile.pay.pay.channel.wxpay.WxpayPaymentService;
import cn.lingyangwl.agile.pay.pay.channel.wxpay.utils.WxpayKit;
import cn.lingyangwl.agile.pay.pay.channel.wxpay.utils.WxpayV3Util;
import cn.lingyangwl.agile.pay.pay.model.bo.MchAppConfigContext;
import cn.lingyangwl.agile.pay.pay.model.bo.WxServiceWrapper;
import cn.lingyangwl.agile.pay.model.rqrs.pay.AbstractRS;
import cn.lingyangwl.agile.pay.pay.model.rqrs.ChannelRetMsgExt;
import cn.lingyangwl.agile.pay.pay.model.rqrs.payorder.UnifiedOrderExtRQ;
import cn.lingyangwl.agile.pay.pay.model.rqrs.payorder.payway.WxJsapiOrderExtRQ;
import cn.lingyangwl.agile.pay.pay.model.rqrs.payorder.payway.WxJsapiOrderRS;
import com.alibaba.fastjson2.JSONObject;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import org.springframework.stereotype.Service;

/**
 * 微信 jsapi支付
 *
 * @author shenguangyang
 */
@Service("wxpayPaymentByJsapiV3Service") //Service Name需保持全局唯一性
public class WxJsapi extends WxpayPaymentService {

    @Override
    public PayWayCodeEnum getPayWayCode() {
        return PayWayCodeEnum.WX_JSAPI;
    }

    @Override
    public String preCheck(UnifiedOrderExtRQ rq, PayOrder payOrder) {
        // 使用的是V2接口的预先校验
        return null;
    }

    @Override
    public AbstractRS pay(UnifiedOrderExtRQ rq, PayOrder payOrder, MchAppConfigContext mchAppConfigContext) throws Exception {

        WxJsapiOrderExtRQ bizRQ = (WxJsapiOrderExtRQ) rq;
        WxServiceWrapper wxServiceWrapper = (WxServiceWrapper) configContextQueryService.getClientWrapper(this.getIfCode(), mchAppConfigContext);
        WxPayService wxPayService = wxServiceWrapper.getWxPayService();
        wxPayService.getConfig().setTradeType(WxPayConstants.TradeType.JSAPI);

        // 构造请求数据
        JSONObject reqJSON = buildV3OrderRequest(wxPayService, payOrder, mchAppConfigContext);

        // wxPayConfig 添加子商户参数
        if (mchAppConfigContext.isIsvsubMch()) {
            wxPayService.getConfig().setSubMchId(reqJSON.getString("sub_mchid"));
            if (StringUtils.isNotBlank(reqJSON.getString("sub_appid"))) {
                wxPayService.getConfig().setSubAppId(reqJSON.getString("sub_appid"));
            }
        }

        String reqUrl;
        if (mchAppConfigContext.isIsvsubMch()) { // 特约商户
            reqUrl = WxpayV3Util.ISV_URL_MAP.get(WxPayConstants.TradeType.JSAPI);
            reqJSON.put("payer", WxpayV3Util.processIsvPayer(reqJSON.getString("sub_appid"), bizRQ.getOpenid()));
        } else {
            reqUrl = WxpayV3Util.NORMALMCH_URL_MAP.get(WxPayConstants.TradeType.JSAPI);
            JSONObject payer = new JSONObject();
            payer.put("openid", bizRQ.getOpenid());
            reqJSON.put("payer", payer);
        }

        // 构造函数响应数据
        WxJsapiOrderRS res = new WxJsapiOrderRS();
        ChannelRetMsgExt channelRetMsgExt = new ChannelRetMsgExt();
        res.setChannelRetMsg(channelRetMsgExt);

        // 调起上游接口：
        // 1. 如果抛异常，则订单状态为： 生成状态，此时没有查单处理操作。 订单将超时关闭
        // 2. 接口调用成功， 后续异常需进行捕捉， 如果 逻辑代码出现异常则需要走完正常流程，此时订单状态为： 支付中， 需要查单处理。
        try {
            JSONObject resJSON = WxpayV3Util.unifiedOrderV3(reqUrl, reqJSON, wxPayService);

            res.setPayInfo(resJSON.toJSONString());

            // 支付中
            channelRetMsgExt.setChannelState(ChannelRetMsgExt.ChannelState.WAITING);

        } catch (WxPayException e) {
            //明确失败
            channelRetMsgExt.setChannelState(ChannelRetMsgExt.ChannelState.CONFIRM_FAIL);
            WxpayKit.commonSetErrInfo(channelRetMsgExt, e);
        }
        return res;
    }

}
